package bll

import (
	"errors"
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"jgt-oper/src/util"
	"time"
)

// Role 角色管理
type Role struct {
	RoleModel model.IRole `inject:"IRole"`
}

// QueryPage 查询分页数据
func (a *Role) QueryPage(params schema.RoleQueryParam, pageIndex, pageSize uint) (int64, []*schema.RoleQueryResult, error) {
	return a.RoleModel.QueryPage(params, pageIndex, pageSize)
}

// QuerySelect 查询选择数据
func (a *Role) QuerySelect(params schema.RoleSelectParam) ([]*schema.RoleSelect, error) {
	return a.RoleModel.QuerySelect(params)
}

// QueryMenuIDsByIDs 根据ID列表查询菜单ID列表
func (a *Role) QueryMenuIDsByIDs(recordIDs []string) ([]string, error) {
	items, err := a.RoleModel.QueryByIDs(recordIDs)
	if err != nil {
		return nil, err
	}

	var menuIDs []string
	for _, item := range items {
		menuIDs = append(menuIDs, item.MenuIDs...)
	}
	return menuIDs, nil
}

// Get 精确查询数据
func (a *Role) Get(recordID string) (*schema.Role, error) {
	return a.RoleModel.Get(recordID)
}

// Create 创建数据
func (a *Role) Create(item *schema.Role) error {
	exists, err := a.RoleModel.CheckName(item.Name)
	if err != nil {
		return err
	} else if exists {
		return errors.New("角色名称已经存在")
	}

	item.ID = 0
	item.RecordID = util.UUID()
	item.Created = time.Now().Unix()
	item.Deleted = 0
	return a.RoleModel.Create(item)
}

// Update 更新数据
func (a *Role) Update(recordID string, item *schema.Role) error {
	oldItem, err := a.Get(recordID)
	if err != nil {
		return err
	} else if oldItem == nil {
		return errors.New("无效的数据")
	}

	if item.Name != oldItem.Name {
		exists, verr := a.RoleModel.CheckName(item.Name)
		if verr != nil {
			return verr
		} else if exists {
			return errors.New("角色名称已经存在")
		}
	}

	info := util.StructToMap(item)
	delete(info, "id")
	delete(info, "record_id")
	delete(info, "creator")
	delete(info, "created")
	delete(info, "deleted")

	return a.RoleModel.Update(recordID, info)
}

// UpdateStatus 更新状态
func (a *Role) UpdateStatus(recordID string, status int) error {
	info := map[string]interface{}{
		"status": status,
	}
	return a.RoleModel.Update(recordID, info)
}

// Delete 删除数据
func (a *Role) Delete(recordID string) error {
	return a.RoleModel.Delete(recordID)
}
